package stack;


/**
 * @author huangxin
 * @date 2019/6/22-11:58
 */
public class LinkedListStackDemo {
    public static void main(String[] args) {
        LinkedListStack stack = new LinkedListStack(3);

        Node node = null;
        for (int i = 0; i < 5; i++) {
            node = new Node(i, i + "");
            stack.push(node);
        }
        stack.list();

        System.out.println("取出的为:" + stack.pop());
        System.out.println("取出的为:" + stack.pop());
        System.out.println("取出的为:" + stack.pop());
        stack.list();
    }
}

class LinkedListStack {
    Node top = new Node(0, "");
    int maxSize;

    public boolean isFill() {
        return getLength() == maxSize;
    }

    public LinkedListStack(int maxSize) {
        this.maxSize = maxSize;
    }

    public boolean isEmpty() {
        return top.no == 0;
    }

    public int getLength() {
        Node temp = top;
        int count = 0;
        while (temp.no != 0) {
            count++;
            temp = temp.pre;
        }
        return count;
    }

    public void push(Node ele) {
        if (ele.no == 0) {
            System.out.println("id不能为0");
        }
        if (isFill()) {
            System.out.println("栈已满");
            return;
        }
        //设置栈顶的元素
        top.next = ele;
        top.next.pre = top;
        //后移
        top = top.next;
    }

    public Node pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈为空");
        }
        //保存元素指针
        Node result = top;
        //top指针往栈底移动
        top = top.pre;
        return result;
    }

    public void list() {
        if (isEmpty()) {
            System.out.println("栈为空,没有数据");
        }
        //从栈顶开始遍历
        Node temp = top;
        while (temp.no != 0) {
            System.out.println(temp);
            temp = temp.pre;
        }
    }
}

class Node {
    int no;
    String name;
    Node next;
    Node pre;

    @Override
    public String toString() {
        return "Node{" +
                "no=" + no +
                ", name='" + name + '\'' +
                '}';
    }

    public Node(int no, String name) {
        this.no = no;
        this.name = name;
    }

    public int removePalindromeSub(String s) {
        if (s.length() == 0) {
            return 0;
        }


        int i = 0;
        int j = s.length() - 1;

        while (i <= j) {
            if (s.charAt(i)!=s.charAt(j)) {
                return 2;
            }
            i++;
            j--;
        }

        return 1;
    }
}


